package com.smartlifev30.mvp.module;

import android.content.Context;

import com.smartlifev30.Constants;
import com.smartlifev30.baiwei.App;
import com.smartlifev30.baiwei.Config;
import com.smartlifev30.network.BaseCallBack;
import com.smartlifev30.utils.SharedPreferencesUtil;

import smartlifev30.com.sdk.api.CallBack;
import smartlifev30.com.sdk.api.service_app.IUserMgmt;
import smartlifev30.com.sdk.api.service_app.UserMgmtImpl;
import smartlifev30.com.sdk.bean.response.LoginResponse;
import smartlifev30.com.sdk.net.baiwei.NetManager;

/**
 *
 * @author tys
 * @date 2018/8/14
 */

public class LoginModule implements ILoginModule {

    private IUserMgmt userMgmt;

    @Override
    public String getServerToken(Context context) {
        return SharedPreferencesUtil.getString(context, SharedPreferencesUtil.REMOTE_TOKEN);
    }

    @Override
    public String getUserName(Context context) {
        return SharedPreferencesUtil.getString(context, SharedPreferencesUtil.USER_NAME);
    }

    @Override
    public String getPassword(Context context) {
        return SharedPreferencesUtil.getString(context, SharedPreferencesUtil.USER_PWD);
    }

    @Override
    public void loginServer(String user, String pwd, BaseCallBack<LoginResponse> callBack) {
        IUserMgmt userMgmt = getUserMgmt();
        userMgmt.loginByPwd(user, pwd, Constants.channelID, Constants.appId, callBack);
    }

    @Override
    public void saveLoginInfo(String user, String pwd, LoginResponse response) {
        String token = response.getResult().getToken();
        //用于心跳
        NetManager instance = NetManager.getInstance();
        instance.setUserAndToken(user, token);

        Config config = Config.getInstance();
        config.setUserName(user);
        config.setRemoteToken(token);

        SharedPreferencesUtil.putString(App.getInstance(), SharedPreferencesUtil.USER_NAME, user);
        SharedPreferencesUtil.putString(App.getInstance(), SharedPreferencesUtil.USER_PWD, pwd);
        SharedPreferencesUtil.putString(App.getInstance(), SharedPreferencesUtil.REMOTE_TOKEN, token);

    }

    @Override
    public void loginServerByToken(String user, String token, CallBack<LoginResponse> callBack) {
        IUserMgmt userMgmt = getUserMgmt();
        userMgmt.loginByToken(user, token, callBack);
    }

    @Override
    public void saveLoginInfoByToken(String user, String token) {
        NetManager instance = NetManager.getInstance();
        instance.setUserAndToken(user, token);

        Config config = Config.getInstance();
        config.setUserName(user);
        config.setRemoteToken(token);
    }

    private IUserMgmt getUserMgmt() {
        if (userMgmt == null) {
            userMgmt = new UserMgmtImpl();
        }
        return userMgmt;
    }
}
